import json
from PyQt6.QtWidgets import (QMainWindow, QWidget, QSplitter, QVBoxLayout, 
                                    QMenuBar, QMenu, QTreeView, QTabWidget, 
                                    QStatusBar, QHBoxLayout, QMessageBox,
                                    QFileDialog)
from PyQt6.QtCore import QFileInfo, QTimer
from logger import logger
from config import ROOT_DIR
from file_system import FileSystemPanel
from code_viewer import TabViewer
from chat_panel import ChatPanel
from ai_service import AIService
from settings_dialog import SettingsDialog
from PyQt6.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        logger.info("初始化主窗口")
        self.ai_service = AIService()
        self.root_dir = ROOT_DIR
        self.init_ui()

    def init_ui(self):
        # 设置窗口标题和初始大小
        self.setWindowTitle('AI Engineer Desktop')
        self.resize(1200, 800)
        
        # 创建菜单栏和状态栏
        self.create_menu_bar()
        self.create_status_bar()

        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        layout = QVBoxLayout(central_widget)
        
        # 创建水平分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        self.splitter = splitter  # 保存为实例变量
        
        # 左侧面板 - 文件管理
        # 创建文件树视图
        self.file_tree = QTreeView()
        self.file_tree.setMinimumWidth(200)
        
        # 初始化文件面板
        self.file_panel = FileSystemPanel(self)  # 保存为实例变量
        splitter.addWidget(self.file_panel)
        
        # 中央面板 - 代码查看区域
        self.tab_widget = QTabWidget()
        self.tab_viewer = TabViewer(self.tab_widget)  # 创建标签页管理器
        splitter.addWidget(self.tab_widget)
        
        # 右侧面板 - AI对话区域
        self.chat_panel = ChatPanel(self.ai_service)
        self.chat_panel.setMinimumWidth(300)
        splitter.addWidget(self.chat_panel)
        
        # 设置分割器的初始比例
        splitter.setStretchFactor(0, 1)  # 文件树
        splitter.setStretchFactor(1, 2)  # 代码查看
        splitter.setStretchFactor(2, 1)  # 对话区域
        
        # 将分割器添加到布局
        layout.addWidget(splitter)
        
        # 连接文件树的点击信号
        self.file_tree.clicked.connect(self.on_file_clicked)
        
    def on_file_clicked(self, index):
        """处理文件点击事件"""
        if not index.isValid():
            return
            
        # 获取文件路径
        file_path = self.file_panel.model.filePath(index)
        
        # 确保是文件而不是目录
        file_info = QFileInfo(file_path)
        if file_info.isFile():
            # 在新标签页中打开文件
            self.tab_viewer.open_file(file_path)

    def create_status_bar(self):
        """创建状态栏"""
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage('就绪')

    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        new_session_action = file_menu.addAction('新建会话')
        new_session_action.triggered.connect(self.new_session)
        
        import_session_action = file_menu.addAction('导入会话')
        import_session_action.triggered.connect(self.import_session)
        
        # 设置菜单
        settings_menu = menubar.addMenu('设置')
        # AI供应商子菜单
        ai_provider_menu = settings_menu.addMenu('AI供应商配置')
        
        # 设置动作
        settings_action = ai_provider_menu.addAction('配置AI服务')
        settings_action.triggered.connect(self.show_settings_dialog)
    def new_session(self):
        """新建会话"""
        logger.info("尝试新建会话")
        reply = QMessageBox.question(
            self,
            '新建会话',
            '确定要清空当前会话吗？',
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.chat_panel.clear_all()
            logger.info("新建会话成功")
            self.statusBar.showMessage('已新建会话')

    def import_session(self):
        """导入会话记录"""
        logger.info("开始导入会话")
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择会话文件",
            "",
            "JSON文件 (*.json)"
        )
        
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    
                if isinstance(data, list):
                    self.chat_panel.conversation_history = data
                    self.chat_panel.clear_all()
                    
                    # 重新显示所有消息
                    for msg in data:
                        if msg['role'] in ['user', 'assistant']:
                            self.chat_panel.append_message(
                                msg['content'],
                                is_user=(msg['role'] == 'user')
                            )
                            
                    logger.info(f"会话导入成功: {file_path}")
                    self.statusBar.showMessage('会话导入成功')
                else:
                    raise ValueError("无效的会话文件格式")
                    
            except Exception as e:
                error_msg = f"导入会话失败: {str(e)}"
                logger.error(error_msg)
                QMessageBox.critical(
                    self,
                    "错误",
                    error_msg
                )

    def show_settings_dialog(self):
        """显示AI服务配置对话框"""
        logger.info("打开AI服务配置对话框")
        dialog = SettingsDialog(self.ai_service, self)
        if dialog.exec():
            logger.info("AI服务配置已更新")
            self.statusBar.showMessage('AI服务配置已更新')
